import CONFIG from './config.js';

class ApiService {
    static async generateChineseName(englishName) {
        const prompt = `As a Chinese name expert, generate 3 Chinese names for the English name "${englishName}". Return ONLY a JSON object in the following format, without any additional text or explanation:

{
    "names": [
        {
            "chinese": "中文名字",
            "pinyin": "Zhong Wen Ming",
            "characters": {
                "中": "meaning of 中",
                "文": "meaning of 文",
                "明": "meaning of 明"
            },
            "cultural": "cultural significance",
            "personality": "personality traits",
            "english_meaning": "English explanation"
        }
    ]
}

Requirements for the names:
1. Match English pronunciation
2. Use positive meanings
3. Follow Chinese naming conventions
4. Include cultural elements`;

        try {
            // 生成 JWT token
            const apiKey = CONFIG.API_KEY;
            const [id, secret] = apiKey.split('.');
            const header = {
                "alg": "HS256",
                "sign_type": "SIGN"
            };
            const payload = {
                "api_key": id,
                "exp": Math.floor(Date.now() / 1000) + 60,
                "timestamp": Math.floor(Date.now() / 1000)
            };

            const token = await this.generateJWT(header, payload, secret);

            const response = await fetch(CONFIG.API_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    model: CONFIG.MODEL,
                    messages: [
                        {
                            role: "system",
                            content: "You are a Chinese name expert. Always respond with valid JSON only, no additional text."
                        },
                        {
                            role: "user",
                            content: prompt
                        }
                    ],
                    temperature: 0.7,
                    top_p: 0.95,
                    max_tokens: 1500
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(`API request failed: ${errorData.error || response.statusText}`);
            }

            const data = await response.json();
            
            // 检查API响应格式
            if (!data.choices || !data.choices[0] || !data.choices[0].message || !data.choices[0].message.content) {
                console.error('Unexpected API response format:', data);
                throw new Error('Unexpected API response format');
            }

            const content = data.choices[0].message.content.trim();
            console.log('Raw API response:', content); // 调试输出

            try {
                // 尝试解析JSON响应
                const parsedContent = JSON.parse(content);
                
                // 验证响应格式
                if (!parsedContent.names || !Array.isArray(parsedContent.names)) {
                    throw new Error('Response missing names array');
                }

                // 验证每个名字对象的格式
                parsedContent.names.forEach((name, index) => {
                    if (!name.chinese || !name.pinyin || !name.characters) {
                        throw new Error(`Name at index ${index} is missing required fields`);
                    }
                });

                return parsedContent;
            } catch (parseError) {
                console.error('Error parsing content:', parseError);
                console.error('Content that failed to parse:', content);
                
                // 尝试清理内容中的特殊字符
                const cleanedContent = content
                    .replace(/^\s*```json\s*/, '') // 移除开头的 ```json
                    .replace(/\s*```\s*$/, '');    // 移除结尾的 ```
                
                try {
                    const reParsedContent = JSON.parse(cleanedContent);
                    return reParsedContent;
                } catch (e) {
                    throw new Error('Failed to parse API response after cleaning');
                }
            }
        } catch (error) {
            console.error('Error generating Chinese name:', error);
            throw error;
        }
    }

    static async generateJWT(header, payload, secret) {
        const encodeBase64Url = (obj) => {
            return btoa(JSON.stringify(obj))
                .replace(/\+/g, '-')
                .replace(/\//g, '_')
                .replace(/=/g, '');
        };

        const encodedHeader = encodeBase64Url(header);
        const encodedPayload = encodeBase64Url(payload);

        const signatureInput = encodedHeader + '.' + encodedPayload;
        const encoder = new TextEncoder();
        const keyData = encoder.encode(secret);
        const signatureBuffer = await crypto.subtle.importKey(
            'raw',
            keyData,
            { name: 'HMAC', hash: 'SHA-256' },
            false,
            ['sign']
        );
        const signature = await crypto.subtle.sign(
            'HMAC',
            signatureBuffer,
            encoder.encode(signatureInput)
        );

        const signatureBase64 = btoa(String.fromCharCode(...new Uint8Array(signature)))
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=/g, '');

        return `${encodedHeader}.${encodedPayload}.${signatureBase64}`;
    }
}

export default ApiService;
